package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 螺旋矩阵54 {

    public static void main(String[] args) {
        int[][] matrix = new int[3][4];
        int index = 1;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = index;
                index++;
            }
        }
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + "  ");
            }
            System.out.println();
        }
        List<Integer> list = spiralOrder(matrix);
        System.out.println(list.toString());
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if(matrix == null || matrix.length <= 0){
            return list;
        }
        int left = 0;
        int right = matrix[0].length - 1; // 列
        int top = 0;
        int buttom = matrix.length - 1; // 行
        String flag = "left";
        while (left <= right && top <= buttom) {
            if(flag.equals("left")) {
                for (int i = left; i <=right; i++) {
                    list.add(matrix[top][i]);
                }
                top++;
                flag = "down";
            }
            if(left > right || top > buttom) {
                break;
            }
            if(flag.equals("down")) {
                for (int i = top; i <= buttom; i++) {
                    list.add(matrix[i][right]);
                }
                right--;
                flag = "right";
            }
            if(left > right || top > buttom) {
                break;
            }
            if(flag.equals("right")) {
                for (int i = right; i >= left; i--) {
                    list.add(matrix[buttom][i]);
                }
                buttom--;
                flag = "up";
            }
            if(left > right || top > buttom) {
                break;
            }
            if(flag.equals("up")) {
                for (int i = buttom; i >= top ; i--) {
                    list.add(matrix[i][left]);
                }
                left++;
                flag = "left";
            }
        }
        return list;
    }
}
